<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Service;

use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsStock;

class GoodsStockManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加商品库存信息
     * @param array $data
     * @return GoodsStock
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addGoodsStock(array $data)
    {
        $goodsStock = new GoodsStock();
        $goodsStock->valuesSet($data);

        $this->entityManager->persist($goodsStock);
        $this->entityManager->flush();

        return $goodsStock;
    }

    /**
     * 编辑商品库存
     * @param array $data
     * @param GoodsStock $goodsStock
     * @return GoodsStock
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editGoodsStock(array $data, GoodsStock $goodsStock)
    {
        $goodsStock->valuesSet($data);
        $this->entityManager->flush();

        return $goodsStock;
    }

    /**
     * 商品库存删除
     * @param GoodsStock $goodsStock
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteGoodsStock(GoodsStock $goodsStock)
    {
        $this->entityManager->remove($goodsStock);
        $this->entityManager->flush();

        return true;
    }

    /**
     * 通过商品id删除库存记录
     * @param $goodsId
     */
    public function deleteGoodsStockGoodsId($goodsId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(GoodsStock::class, 's')->where('s.goodsId = :goodsId')->setParameter('goodsId', $goodsId);
        $qb->getQuery()->execute();
    }

    /**
     * 修改商品库存
     * @param $stockNum
     * @param $changeType
     * @param $goodsId
     */
    public function changeGoodsStockNum($stockNum, $changeType, $goodsId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(GoodsStock::class, 's')->set('s.stockNum', 's.stockNum'.$changeType.$stockNum)
            ->where('s.goodsId = :goodsId')->setParameter('goodsId', $goodsId);
        $qb->getQuery()->execute();
    }
}